<?php
declare (strict_types = 1);

namespace app\service;

use app\dao\StudentDao;
use app\exception\ServiceException;
use think\App;
use think\facade\Cache;
use think\facade\Db;

class StudentService
{
    private $studendao;
    public function __construct()
    {
        $this->studendao = new StudentDao();
    }
    public function setCache(){
        $information = $this->studendao
            ->hiddenPassword()
            ->getAll();
        Cache::set('stuInformation',$information,3600);
        return $information;
    }
    public function deleteCache() {
        $result = Cache::get('stuInformation');
        if ($result != null) Cache::delete('stuInformation');
        return true;
    }
    public function getInformation(){
        $result = Cache::get('stuInformation');
        if ($result != null) return $result;
        return $this->setCache();
    }
    public function deleteUser($id){
        try{
            Db::startTrans();
            $result = $this->studendao->delete($id);
            $this->deleteCache();
            Db::commit();
        } catch (\Exception $exception){
            Db::rollback();
            throw new ServiceException('删除失败');
        }
        $this->setCache();
        return $result;
    }

    public function disableStudent($id,$isAdmin){
        try {
            $result = $this->studendao->updateById('status',$isAdmin, $id);
            $this->deleteCache();
        } catch (\Exception $exception) {
            throw new ServiceException('禁用失败');
        }
        $this->setCache();
        return $result;
    }
}
